import axios from 'axios';

const API_URL = '/api/auth';

class AuthService {
  constructor() {
    // 设置axios拦截器
    this.setupInterceptors();
  }

  setupInterceptors() {
    // 请求拦截器
    axios.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    axios.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        if (error.response?.status === 401) {
          // Token过期或无效，清除本地存储并跳转到登录页
          this.removeAuthToken();
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          window.location.href = '/login';
        }
        return Promise.reject(error);
      }
    );
  }

  async login(username, password) {
    const response = await axios.post(`${API_URL}/login`, {
      username,
      password
    });
    return response;
  }

  async register(userData) {
    const response = await axios.post(`${API_URL}/register`, userData);
    return response;
  }

  async updatePassword(id, oldPassword, newPassword) {
    const response = await axios.post(`${API_URL}/updatePassword`, {
      id,
      oldPassword,
      newPassword
    });
    return response;
  }

  setAuthToken(token) {
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
      delete axios.defaults.headers.common['Authorization'];
    }
  }

  removeAuthToken() {
    delete axios.defaults.headers.common['Authorization'];
  }

  getCurrentUser() {
    const userData = localStorage.getItem('user');
    return userData ? JSON.parse(userData) : null;
  }

  getToken() {
    return localStorage.getItem('token');
  }

  isAuthenticated() {
    const token = this.getToken();
    const user = this.getCurrentUser();
    return !!(token && user);
  }
}

export default new AuthService();